#include "threadPool.h"
#include "head.h"
#include "command.h"

int makeWorker(threadPool_t *threadPool){
    for(int i = 0; i < threadPool->workerNum; ++i){
        pthread_create(&threadPool->tidArr[i],NULL,threadFunc,threadPool);
    }
    return 0;
}

void *threadFunc(void *arg){
    threadPool_t *threadPool = (threadPool_t *)arg;
    int isLogin =0;
    user_t user;
    while(1){
        // 取出任务
        pthread_mutex_lock(&threadPool->taskQueue.mutex);
        while(threadPool->exitflag == 0 && threadPool->taskQueue.queueSize == 0){
            pthread_cond_wait(&threadPool->taskQueue.cond, &threadPool->taskQueue.mutex);
        }
        if(threadPool->exitflag != 0){
            printf("child is going to exit!\n");
            pthread_mutex_unlock(&threadPool->taskQueue.mutex);
            pthread_exit(NULL);
        }
        printf("child get a task!\n");
        int netfd = threadPool->taskQueue.pFront->netfd;
        deQueue(&threadPool->taskQueue);
        pthread_mutex_unlock(&threadPool->taskQueue.mutex);
        // 执行任务
        
        if(isLogin ==0)
        {
            if(myLogin(netfd,&user))
            {
                isLogin = 1;
            }
            else
            {
                close(netfd);
            }
        }

        int orderflag;
        char buf[1024] = {0};
        train_state_t train_state_get;
        recv(netfd,&train_state_get,sizeof(train_state_t),0);
        orderflag = train_state_get.state;
        strcpy(buf,train_state_get.buff);
        
        execOrder(orderflag,buf,netfd,&user);
        
        close(netfd);
        
        // 恢复空闲
        printf("child finish a task!\n");
    }
}
